#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "ff.h"
#include "esp_log.h"
#include "lvgl/lvgl.h"

#define TAG "FILE_MANAGER"
#define MAX_PATH_LEN 256
#define MAX_FILES 50

static char current_path[MAX_PATH_LEN]="/";
static lv_obj_t *file_list;
static lv_obj_t *path_label;

typedef struct
{
    char name[64];
    bool is_dir;
} file_item_t;

static file_item_t files[MAX_FILES];
static int file_count = 0;

static void refresh_file_list()
{
    FF_DIR dir;
    FILINFO fno;
    FRESULT res;

    // 清空当前文件列表
    file_count = 0;
    lv_table_set_row_cnt(file_list, 1);

    // 打开目录
    res = f_opendir(&dir, current_path);
    if (res != FR_OK)
    {
        ESP_LOGE(TAG, "无法打开目录: %s (错误码: %d)", current_path, res);
        return;
    }

    // 添加".."上级目录项
    if (strcmp(current_path, "/") != 0)
    {
        strcpy(files[file_count].name, "..");
        files[file_count].is_dir = true;
        file_count++;
    }

    // 读取目录内容
    while (1)
    {
        res = f_readdir(&dir, &fno);
        if (res != FR_OK || fno.fname[0] == 0)
            break;

        if (file_count < MAX_FILES)
        {
            strncpy(files[file_count].name, fno.fname, sizeof(files[0].name));
            files[file_count].is_dir = (fno.fattrib & AM_DIR) ? true : false;
            file_count++;
        }
    }
    f_closedir(&dir);

    // 更新UI列表
    lv_table_set_row_cnt(file_list, file_count + 1);
    for (int i = 0; i < file_count; i++)
    {
        lv_table_set_cell_value(file_list, i, 0, files[i].name);
        lv_table_set_cell_value(file_list, i, 1, files[i].is_dir ? "目录" : "文件");
    }

    // 更新路径显示
    // lv_label_set_text(path_label, current_path);
}

static lv_obj_t *file_path_textbox;

static void file_select_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        // 显示文件列表
        lv_obj_clear_flag(file_list, LV_OBJ_FLAG_HIDDEN);
    }
}

static void file_list_event_cb(lv_event_t *e)
{
    if(!e || !file_list) return;
    
    lv_obj_t *obj = lv_event_get_target(e);
    if(!obj) return;
    
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_VALUE_CHANGED)
    {
        uint32_t row = 0;
        uint32_t col = 0;
        lv_table_get_selected_cell(obj, &row, &col);
      

        if (row < file_count)
        {
            char new_path[512];
            ESP_LOGI(TAG, "点击项: %s (类型: %s)", files[row].name, files[row].is_dir ? "目录" : "文件");
            
            if (strcmp(files[row].name, "..") == 0)
            {
                // 处理上级目录
                char *last_slash = strrchr(current_path, '/');
                if (last_slash != current_path)
                {
                    *last_slash = '\0';
                    ESP_LOGI(TAG, "返回上级目录: %s", current_path);
                }
            }
            else if (files[row].is_dir)
            {
                // 拼接新路径
                snprintf(new_path, sizeof(new_path), "%s/%s", current_path, files[row].name);
                strcpy(current_path, new_path);
                ESP_LOGI(TAG, "进入目录: %s", current_path);
            }
            else
            {
                // 文件处理逻辑
                char full_path[MAX_PATH_LEN * 2];
                snprintf(full_path, sizeof(full_path), "%s/%s", current_path, files[row].name);
                ESP_LOGI(TAG, "选中文件: %s", full_path);
                lv_textarea_set_text(file_path_textbox, full_path);
                lv_obj_add_flag(file_list, LV_OBJ_FLAG_HIDDEN);
                return;
            }
            
            // 刷新列表
            ESP_LOGI(TAG, "刷新目录列表...");
            refresh_file_list();
        }
    }
}

bool is_lvgl_initialized = false;

void create_file_manager(lv_obj_t *parent)
{
    // 创建路径显示
    path_label = lv_label_create(parent);
    lv_obj_align(path_label, LV_ALIGN_TOP_LEFT, 10, 10);
    lv_label_set_long_mode(path_label, LV_LABEL_LONG_SCROLL_CIRCULAR);
    lv_obj_set_width(path_label, LV_PCT(90));
    lv_label_set_text(path_label, "download path:");
    // 创建文件路径输入框
    file_path_textbox = lv_textarea_create(parent);
    lv_obj_set_size(file_path_textbox, LV_PCT(90), 40);
    lv_obj_align_to(file_path_textbox, path_label, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 10);
    lv_textarea_set_placeholder_text(file_path_textbox, "click to select file...");
    lv_obj_add_event_cb(file_path_textbox, file_select_cb, LV_EVENT_CLICKED, NULL);
    lv_label_set_long_mode(path_label, LV_LABEL_LONG_SCROLL_CIRCULAR);
    lv_obj_set_width(path_label, LV_PCT(90));

    // 创建文件列表
    file_list = lv_table_create(parent);
    lv_obj_set_size(file_list, LV_PCT(90), LV_PCT(80));
    lv_obj_align_to(file_list, file_path_textbox, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 20);
    lv_obj_add_flag(file_list, LV_OBJ_FLAG_HIDDEN); // 初始隐藏
    lv_table_set_col_width(file_list, 0, LV_PCT(70));
    lv_table_set_col_width(file_list, 1, LV_PCT(30));
    lv_table_set_col_cnt(file_list, 2);
    lv_obj_add_event_cb(file_list, file_list_event_cb, LV_EVENT_VALUE_CHANGED, NULL);

    // 设置表头
    lv_table_set_cell_value(file_list, 0, 0, "name");
    lv_table_set_cell_value(file_list, 0, 1, "type");

    // 初始刷新
    refresh_file_list();
}
